<?php
/**
 * Created by Veyron
 * User: Vy
 * motto:现在的拼搏 为了更好的明天
 * Class: AliSms 阿里云短信发送
 * day:  2020/1/17
 * Time: 10:57
 */
declare(strict_types=1);
namespace app\common\lib\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;

class AliSms implements BaseSms
{
    /**
     * 阿里云发送短信验证码场景
     * @param string $phone_number
     * @param int $code
     * @return bool
     * @throws ClientException
     */
    public static function sendCode(string $phone_number,int $code) : bool {
        if(empty($phone_number) || empty($code)){
            return false;
        }
        AlibabaCloud::accessKeyClient(config('aliyun.access_key_id'), config('aliyun.access_secret'))
            ->regionId(config('aliyun.region_id'))
            ->asDefaultClient();

        try {

            $templateParam = [
                'code' => $code
            ];

            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host(config('aliyun.host'))
                ->options([
                    'query' => [
                        'RegionId'       => config('aliyun.region_id'),
                        'PhoneNumbers'   => $phone_number,
                        'SignName'       => config('aliyun.sign_name'),
                        'TemplateCode'   => config('aliyun.template_code'),
                        'TemplateParam'  => json_encode($templateParam),
                    ],
                ])
                ->request();
            $result = $result->toArray();
            //发送成功返回数据 Array
            //(
            //    [Message
            //] => OK
            //    [RequestId
            //] => F3429382-FA53-4A32-80C6-3F1664506943
            //    [BizId
            //] => 453511379510328355^0
            //    [Code
            //] => OK
            //)
            if($result['Code'] == 'OK'){
                Log::info("alisms-sendCode-result-{$phone_number}".json_encode($result));
            }else{
                Log::error("alisms-sendCode-result-{$phone_number}".json_encode($result));
            }

        } catch (ClientException $e) {
            //todo 记录日志
            Log::error("alisms-sendCode-ClientException-{$phone_number}".json_encode($e->getMessage()));
            return false;
//            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            //todo 记录日志
            Log::error("alisms-sendCode-ServerException-{$phone_number}".json_encode($e->getMessage()));
            return false;
//            echo $e->getErrorMessage() . PHP_EOL;
        }
        return true;
    }
}
